package com.example.shushiyunsst.fragment.main.home.child.icon_sst

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.arch.core.executor.ArchTaskExecutor
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.timer.BaseTimerTask
import com.example.library_common.utils.timer.ITimerListener
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.CurrencyTransferBuyStatusFragmentBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.*
import com.example.shushiyunsst.util.clipboard
import com.example.shushiyunsst.util.push.helper.PushHelper
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.Preference

import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.ImageViewerPopupView
import com.lxj.xpopup.interfaces.XPopupImageLoader
import java.io.File
import java.util.*

class CurrencyTransferBuyStatusFragment :
    BaseDataBindingFragment<CurrencyTransferBuyStatusFragmentBinding>(),
    View.OnClickListener, ITimerListener {

    companion object {
        fun newInstance(mBean: CurrencyOrderInfoBean): CurrencyTransferBuyStatusFragment {
            val args = Bundle()
            args.putSerializable("mBean", mBean)
            val fragment = CurrencyTransferBuyStatusFragment()
            fragment.arguments = args
            return fragment
        }
    }


    private var mTimerTask: BaseTimerTask? = null

    private var mTimer: Timer? = null

    private var timer = 15 * 60

    private val handler: Handler = Handler(Looper.getMainLooper())

    private var mBean: CurrencyOrderInfoBean? = null

//    private var payType = BANK_PAY

//    private var orderInfoBean: CurrencyOrderInfoBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBean = arguments?.getSerializable("mBean") as CurrencyOrderInfoBean
        mBean?.payWay = BANK_PAY
    }

    override fun layoutId(): Int {
        return R.layout.currency_transfer_buy_status_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = mBean?.order?.statusDesc
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        viewBinder.onViewClick = this

        viewBinder.bean = mBean

//
//        onTimer()
        startTimer()


        showPay()
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.bankCardPayBankNo -> {
                clipboard("bankCardPayBankNo", mBean?.payment?.bankNo ?: "")
            }

            R.id.bankCardPayRealName -> {
                clipboard("bankCardPayRealName", mBean?.payment?.realName ?: "")
            }

            R.id.bankCardPayBankNameChild -> {
                clipboard("bankCardPayBankNameChild", mBean?.payment?.bankNameChild ?: "")
            }

            R.id.bankCardPayBankName -> {
                clipboard("bankCardPayBankNameChild", mBean?.payment?.bankName ?: "")
            }

            R.id.weiChatPayAccount -> {
                clipboard("weiChatPayAccount", mBean?.payment?.wxAccount ?: "")
            }

            R.id.weiChatPayRealName -> {
                clipboard("weiChatPayRealName", mBean?.payment?.realName ?: "")
            }

            R.id.aliPayAccount -> {
                clipboard("aliPayAccount", mBean?.payment?.alipayAccount ?: "")
            }

            R.id.aliPayRealName -> {
                clipboard("aliPayAccount", mBean?.payment?.realName ?: "")
            }

            R.id.aliPayPic -> {
                val imageViewerPopupView = ImageViewerPopupView(_mActivity)
                imageViewerPopupView.setImageUrls(listOf(mBean?.payment?.alipayUrl))
                imageViewerPopupView.setXPopupImageLoader(object : XPopupImageLoader {
                    override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
                        GlideApp.with(this@CurrencyTransferBuyStatusFragment)
                            .load(uri)
                            .centerInside()
                            .into(imageView)
                    }

                    override fun getImageFile(context: Context, uri: Any): File {
                        return File(uri.toString())
                    }
                })
                XPopup.Builder(_mActivity)
                    .asCustom(imageViewerPopupView)
                    .show()
            }

            R.id.weiChatPayPic -> {
                val imageViewerPopupView = ImageViewerPopupView(_mActivity)
                imageViewerPopupView.setImageUrls(listOf(mBean?.payment?.wxUrl))
                imageViewerPopupView.setXPopupImageLoader(object : XPopupImageLoader {
                    override fun loadImage(position: Int, uri: Any, imageView: ImageView) {
                        GlideApp.with(this@CurrencyTransferBuyStatusFragment)
                            .load(uri)
                            .centerInside()
                            .into(imageView)
                    }

                    override fun getImageFile(context: Context, uri: Any): File {
                        return File(uri.toString())
                    }
                })
                XPopup.Builder(_mActivity)
                    .asCustom(imageViewerPopupView)
                    .show()
            }

            R.id.aliPayPaying_way -> {
                if (mBean?.payment?.isSupportWx==1){
                    mBean?.payWay = WEI_CHAT_PAY
                    showPay()
                }else if(mBean?.payment?.isSupportBank==1){
                    mBean?.payWay = BANK_PAY
                    showPay()
                }

            }
            R.id.weiChatPayPaying_way -> {
                if (mBean?.payment?.isSupportBank==1){
                    mBean?.payWay = BANK_PAY
                    showPay()
                }else if (mBean?.payment?.isSupportAipay==1){
                    mBean?.payWay = A_LI_PAY
                    showPay()
                }

            }
            R.id.bankCardPayPaying_way -> {
                if (mBean?.payment?.isSupportAipay==1){
                    mBean?.payWay = A_LI_PAY
                    showPay()
                }else if (mBean?.payment?.isSupportWx==1){
                    mBean?.payWay = WEI_CHAT_PAY
                    showPay()
                }

            }
            R.id.take_order -> {
                XPopup.Builder(_mActivity)
                    .asCustom(
                        CurrencyTransferBuyStatusPop(_mActivity)
                            .setBean(mBean)
                            .setCallBackListener(object :
                                CurrencyTransferBuyStatusPop.CallBackListener {
                                override fun sureAction() {
//                                    val userInfo =
//                                        UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

                                    val map = mapOf(
                                        "payType" to mBean?.payWay,
                                        "toid" to mBean?.order?.toid
                                    )

                                    RestClient.builder()
                                        .raw(JSON.toJSONString(map))
                                        .url(R.string.saveTxBuyOrderPay)
                                        .success {

                                            parseSaveTxBuyOrderPay(it)
                                        }
                                        .failure {
                                            Toast.makeText(_mActivity, "发送订单失败", Toast.LENGTH_SHORT).show()
                                            onBackPressedSupport()
                                        }.error { _, msg ->
                                            Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                                            onBackPressedSupport()
                                        }
                                        .build().post()

                                }

                            })
                    )
                    .show()

            }
        }
    }


    private fun parseSaveTxBuyOrderPay(it: String?) {
        val obj = JSON.parseObject(it, SaveTxBuyOrderPayBean::class.java)
        pushMsg(obj)
        startWithPop(CollectedCoinsFragment.newInstance("${obj.order.toid}"))
    }

    @SuppressLint("RestrictedApi")
    private fun pushMsg(obj: SaveTxBuyOrderPayBean) {
        ArchTaskExecutor.getIOThreadExecutor().execute {
            try {
                val deviceTokens = obj.pushMsg?.deviceToken ?: ""
//                val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
                obj.pushMsg.type = FU_KUANG
                obj.pushMsg.orderId = obj.order.txNo
                val pushHelper = PushHelper()
                val broadcast = PushHelper.getAndroidBroadcast()
                broadcast.setTitle("SST放款")
                broadcast.setDeviceToken(deviceTokens)
                broadcast.setPlaySound(true)
                broadcast.setTicker("SST放款")
                broadcast.setTitle("SST放款")
                broadcast.setText("${obj.pushMsg?.contentDesc}")
                broadcast.setCustomField(JSON.toJSONString(obj.pushMsg))
                pushHelper.sendAndroidBroadcast(broadcast)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun showPay() {
        when (mBean?.payWay) {
            A_LI_PAY -> {
                if (mBean?.payment?.isSupportAipay==1){
                    viewBinder.aliPayLayout.visibility = View.VISIBLE
                    viewBinder.weiChatPayLayout.visibility = View.GONE
                    viewBinder.bankCardPayLayout.visibility = View.GONE
                }

            }
            WEI_CHAT_PAY -> {
                if (mBean?.payment?.isSupportWx==1){
                    viewBinder.aliPayLayout.visibility = View.GONE
                    viewBinder.weiChatPayLayout.visibility = View.VISIBLE
                    viewBinder.bankCardPayLayout.visibility = View.GONE
                }

            }
            BANK_PAY -> {
                if (mBean?.payment?.isSupportBank==1){
                    viewBinder.aliPayLayout.visibility = View.GONE
                    viewBinder.weiChatPayLayout.visibility = View.GONE
                    viewBinder.bankCardPayLayout.visibility = View.VISIBLE
                }

            }
        }
//        mBean?.payWay = payType
    }

    private fun startTimer() {
        if (mTimerTask !== null) return


        mTimer = Timer()
        mTimerTask = BaseTimerTask(this)
        mTimer?.schedule(mTimerTask, 1000, 1000)
    }

    private fun stopTimer() {

        if (mTimer != null) {
            mTimer?.cancel()
            mTimer = null
        }

        if (mTimerTask != null) {
            mTimerTask?.cancel()
            mTimerTask = null
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onTimer() {
        handler.post {
            timer--
            if (timer <= 0) {
                stopTimer()
                onBackPressedSupport()
            } else {
                viewBinder.cancelTv.text = "${timerStr()}后自动取消"
            }

        }
    }

    private fun timerStr(): String {
        if (timer < 60) {
            return "$timer 秒"
        }

        val sec = timer % 60
        val min = timer / 60
        return "$min 分 $sec 秒"
    }

    override fun onDestroy() {
        super.onDestroy()
        stopTimer()
    }
}